package com.social.controller;

import com.alibaba.fastjson.JSON;
import com.social.pojo.*;
import com.social.service.*;
import com.social.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 角色管理
 */
@Controller
@RequestMapping("Role")
public class RoleController {
    /**
     * Role 业务层
     */
    @Autowired
    private RoleService roleService;
    /**
     * User 业务层
     */
    @Autowired
    private UserService userService;
    /**
     * UserRole 业务层
     */
    @Autowired
    private UserRoleService userRoleService;
    /**
     * RolePermission 业务层
     */
    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 查所有
     *
     * @param session 作用域
     * @return 查询状态
     */
    @RequestMapping(value = "selectAll", produces = "text/application;charset=utf-8")
    @ResponseBody
    public String selectAll(HttpSession session) {
        try {
            List<Role> roles = roleService.selectAll();
            session.setAttribute("role", roles);
        } catch (Exception e) {
            return JSON.toJSONString(false);
        }
        return JSON.toJSONString(true);
    }

    /**
     * 根据用户名查询
     *
     * @param username 用户名
     * @return 查询数据
     */
    @RequestMapping(value = "selectByUsername", produces = "text/application;charset=utf-8")
    @ResponseBody
    public String selectByUsername(String username) {
        User user = userService.selectByUsername(username);
        return JSON.toJSONString(user);
    }

    /**
     * @param uid userId
     * @param rid roleId
     * @return 修改状态
     */
    @RequestMapping("update")
    @ResponseBody
    public String update(Integer uid, Integer rid) {
        System.out.println(uid + "," + rid);
        //用户对应角色
        int status = userRoleService.update(uid, rid);
        //查询角色对应权限
        List<RolePermissionKey> select = rolePermissionService.select(rid, rid);
        if (select == null) {
            RolePermissionKey rolePermissionKey = new RolePermissionKey(rid, rid);
            rolePermissionService.insertSelective(rolePermissionKey);
        }
        JsonUtil jsonUtil = new JsonUtil();
        //设置状态
        Boolean restates = jsonUtil.getRestates(status);
        return JSON.toJSONString(restates);
    }
}
